/**
 * 
 */
package com.henryzhou.cloud.request;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.henryzhou.cloud.AckValue;
import com.henryzhou.cloud.ContentTypeConstants;
import com.henryzhou.cloud.response.GetResponse;
import com.henryzhou.cloud.response.IResponse;

/**
 * @author haozhou
 *
 */
public class GetRequest extends BaseRequest implements IRequest {
	private File saveTo;
	
	public GetRequest(String uri, Map<String, String> headParams) {
		super(new HttpGet(uri));
		if (headParams != null ) {
			for( Map.Entry<String, String> entry : headParams.entrySet() ) {
				getDeletageObject().setHeader(entry.getKey(), entry.getValue());
			}
		}
	}
	
	public HttpGet getDeletageObject() {
		return (HttpGet) getRequest();
	}
	
	public void setObjectDestination(File path) {
		this.saveTo = path;
	}

	@Override
	public IResponse invoke() {
		HttpClient client = new DefaultHttpClient();
		try {
			HttpResponse delegate = client.execute(this.getDeletageObject());
			GetResponse resp = new GetResponse(delegate);
			resp.setStatusCode(delegate.getStatusLine().getStatusCode());
			if (delegate.getStatusLine().getStatusCode() == 200) {
				resp.setAck(AckValue.SUCCESS);
			} else {
				resp.setAck(AckValue.FAILURE);
			}
			
			resp.setContentType(delegate.getEntity().getContentType().getValue());
			InputStream input = null;
			OutputStream output = null;
			try {
				if (resp.getContentType().equals(ContentTypeConstants.XML)) {
					resp.setBody(IOUtils.toString(delegate.getEntity().getContent()));
				} else {
					if (saveTo == null) {
						saveTo = File.createTempFile("googstorage", "");
					}
					output = new FileOutputStream(saveTo);
					IOUtils.copy(delegate.getEntity().getContent(), output);
					resp.setBody(saveTo);
				}
			} finally {
				IOUtils.closeQuietly(input);
				IOUtils.closeQuietly(output);
			}
	            
			return resp;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
